package dao

import (
	"github.com/go-xorm/xorm"

	"im/common"
	"im/errcode"
	"im/model"
	"im/service/orm"
)

type Likes interface {
	// 判断是否存在记录, 如果不存在则添加一条
	Like(userId int64, selector model.LikesSelector) (bool, error)

	// 判断是否存在记录, 如果存在则删除
	UnLike(userId int64, selector model.LikesSelector) (bool, error)
	GetLikeStatus(userId int64, likeType int64, typeIds ...int64) (map[int64]interface{}, error)
}

func NewLikes() Likes {
	return likes{db: orm.GetDB()}

}

type likes struct {
	db *xorm.Engine
}

func (l likes) Like(userId int64, selector model.LikesSelector) (bool, error) {
	exist, err := l.db.Where("user_id=?", userId).
		Where("pr_id=?", selector.PRId).
		Where("type=?", selector.Type).Exist(&model.Likes{})
	if err != nil {
		return exist, errcode.NewError(errcode.DaoFailed, err)
	}
	if exist {
		return true, nil
	}
	_, err = l.db.InsertOne(model.Likes{
		UId:           model.UId{userId},
		LikesSelector: selector,
	})
	if err != nil {
		return false, errcode.NewError(errcode.DaoFailed, err)
	}
	return false, err

}

func (l likes) UnLike(userId int64, selector model.LikesSelector) (bool, error) {
	effected, err := l.db.Where("user_id=?", userId).
		Where("pr_id=?", selector.PRId).
		Where("type=?", selector.Type).Delete(&model.Likes{})
	if err != nil {
		return false, errcode.NewError(errcode.DaoFailed, err)
	}
	if effected == 0 {
		return false, nil
	}
	return true, nil
}
func (l likes) GetLikeStatus(userId int64, likeType int64, replyIds ...int64) (map[int64]interface{}, error) {

	var likeList = []model.Likes{}
	var resp = map[int64]interface{}{}
	if userId <= 0 {
		return resp, nil
	}
	err := l.db.Where("type=?", likeType).Where("user_id=?", userId).In("pr_id", common.ToInterfaceSlice(replyIds)...).Find(&likeList)
	if err != nil {
		return resp, errcode.NewError(errcode.DaoFailed, err)
	}
	for _, row := range likeList {
		resp[row.PRId] = nil
	}
	return resp, nil

}
